import { defineStore } from 'pinia';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { login as userLogin, logout as userLogout } from '@/api/modules/auth/oauth'
import { LoginData } from "@/types/modules/auth";
import { findUserInfo } from '@/api/modules/system/user'
import type { UserInfo } from '@/types/modules/system'
import { UserState } from './types';
import useAppStore from '../app';

// -1 默认用户id, 区别于真正用户，硬编码
const UNKNOWN_ID = -1;
const useUserStore = defineStore('user', {
  persist: true,
  state: (): UserInfo => ({
    id: UNKNOWN_ID,
    username: 'unknown',
    nickname: '未登录',
    gender: 0,
    phone: '',
    email: '',
    roles: [],
    authorities: [],
    avatar: '',
  }),

  getters: {
    userInfo(state: UserInfo): UserInfo {
      return { ...state };
    },
    hasInfo(state: UserInfo): boolean {
      return state.id !== UNKNOWN_ID;
    }
  },

  actions: {
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async info() {
      const res = await findUserInfo();
      this.setInfo(res.data);
    },

    // Login
    async login(loginForm: LoginData) {
      clearToken()
      const res = await userLogin(loginForm);
      setToken(res.data);
    },
    logoutCallBack() {
      clearToken();
      const appStore = useAppStore();
      this.resetInfo();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      try {
        await userLogout();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
